package com.qf.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qf.pojo.RedisKey;
import com.qf.pojo.reqVo.MessageReq;
import com.qf.pojo.respVo.*;
import com.qf.pojo.vo.LiveUser;
import com.qf.service.MessageService;
import com.qf.utils.UserUtils;
import io.rong.RongCloud;
import io.rong.messages.TxtMessage;
import io.rong.methods.message._private.Private;
import io.rong.models.message.PrivateMessage;
import io.rong.models.response.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    UserUtils userUtils;
    @Autowired
    RedisTemplate redisTemplate;

//         * 此处替换成您的appKey
//     */
    private static final String appKey = "8luwapkv8wxcl";
    /**
     * 此处替换成您的appSecret
     */
    private static final String appSecret = "I4BB9FgbDFT";

    /**
     * 通过用户的id获取到对话列表
     * @param request
     * @return
     */
    @Override
    public BaseResp findTalkListByToken(HttpServletRequest request, Map map) {
        //解析出用户的id 使用redis的hash结构进行存储，key值为当前登录用户的id，第二层key为对话的用户id，第三层为用户的信息
        Integer userId = userUtils.getUserId(request);
        //获取用户聊天的具体信息内容
        Object uid = redisTemplate.opsForHash().get(RedisKey.MESSAGE + userId.toString(), map.get("uid").toString());
        //返回前端
        return new BaseResp(1,"ok",uid,null);
    }

    @Override
    public BaseResp sendMsg(MessageReq messageReq,HttpServletRequest request) {
        //进行消息的发送，使用融云 发送信息到客户端
        RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
        //声明发送的模式为 私聊
        Private Private = rongCloud.message.msgPrivate;
        //声明发送的内容是什么
        TxtMessage txtMessage = new TxtMessage(messageReq.getMsg(), messageReq.getMsg());
        //解析出发送消息的用户id
        Integer userId = userUtils.getUserId(request);
        //拼装私聊消息体
        PrivateMessage privateMessage = new PrivateMessage()
                .setSenderId(userId.toString())
                .setTargetId(new String[]{messageReq.getUserid().toString()})
                .setObjectName(txtMessage.getType())
                .setContent(txtMessage);
        try {
            //直接发送消息-》融云-》推送到监听的用户的rong-token的页面中进行展示
            ResponseResult privateResult = Private.send(privateMessage);
            //发送成功后记录到redis中，进行添加

            //声明messageList,对话的集合，判断是否在redis中包含，如果包含则直接从redis中获取
            Object msgList = redisTemplate.opsForHash().get(RedisKey.MESSAGE + userId.toString(), messageReq.getUserid().toString());
           //获取发件人的用户信息
            Object o = redisTemplate.opsForHash().get(RedisKey.USERLOGIN, messageReq.getUserid().toString());
            //转为LiveUser对象
            LiveUser parse = JSONObject.parseObject(JSONObject.toJSONString(o), LiveUser.class);
            FromUser fromUser = new FromUser();
            fromUser.setId(messageReq.getUserid());
            fromUser.setDisplayName(parse.getLoginName());
            fromUser.setAvatar(parse.getPic());
            if (msgList != null) {
                Message message1 = JSONObject.parseObject(JSONObject.toJSONString(msgList), Message.class);
                //获取到message1中的详情聊天信息.进行新增操作
                List<MessageList> messageList = message1.getMessageList();
                MessageList mlist = new MessageList();
                mlist.setSendTime(new Date());
                mlist.setContent(messageReq.getMsg());
                mlist.setId(UUID.randomUUID().toString());
                mlist.setToContactId(messageReq.getUserid());
                mlist.setStatus("success");
                //设置发消息人的信息

                //设置到消息 列表中
                mlist.setFromUser(fromUser);
                messageList.add(mlist);
                message1.setMessageList(messageList);
                //放置在redis中
                redisTemplate.opsForHash().put(RedisKey.MESSAGE + userId.toString(), messageReq.getUserid().toString(), message1);
            }else {
                Message message = new Message();
                message.setLastSendTime(new Date());
                message.setId(messageReq.getUserid());
                message.setLastContent(messageReq.getMsg());
                MessageList mlist = new MessageList();
                mlist.setSendTime(new Date());
                mlist.setContent(messageReq.getMsg());
                mlist.setId(UUID.randomUUID().toString());
                mlist.setToContactId(messageReq.getUserid());
                mlist.setStatus("success");
                List<MessageList> list =new ArrayList<>();

                //设置到消息 列表中
                mlist.setFromUser(fromUser);
                list.add(mlist);
                message.setMessageList(list);
                //放置在redis中
                redisTemplate.opsForHash().put(RedisKey.MESSAGE + userId.toString(), messageReq.getUserid().toString(), message);
            }
        }catch (Exception e){
            return new BaseResp(1, "发送失败！", null, null);
        }
            return new BaseResp(1, "发送成功！", null, null);
        }


    @Override
    public BaseResp findTalkUser(HttpServletRequest request) {
        Integer userId = userUtils.getUserId(request);
        //获取到排除自己的，用户列表
        Map entries = redisTemplate.opsForHash().entries(RedisKey.USERLOGIN);
        Set set = entries.keySet();
        //通过第二层Key循环获取到用户
        List list = new ArrayList<>();
        for (Object obj:set
             ) {
            if (Integer.valueOf(obj.toString()).equals(userId)){
                continue;
            }
            Message message = new Message();
           //进行第二次获取
            Object o = redisTemplate.opsForHash().get(RedisKey.USERLOGIN, obj.toString());
            //转为Liveuser对象
            //转为user对象
            LiveUser parse = JSONObject.parseObject(JSONObject.toJSONString(o), LiveUser.class);
            //放置消息内容
            message.setId(parse.getUserId());
            message.setDisplayName(parse.getLoginName());
            message.setLiveUser(parse);
            //获取到最后一次聊天的信息
            //获取到最后一条信息
            Object o1 = redisTemplate.opsForHash().get(RedisKey.MESSAGE + userId.toString(), obj.toString());
            Message message1 = JSONObject.parseObject(JSONObject.toJSONString(o1), Message.class);
            if (message1!=null){
                List<MessageList> messageList = message1.getMessageList();

                message.setLastContent(messageList.get(messageList.size()-1).getContent());
            }else{
                message.setLastContent("测试测试！");
            }
           //封装到对象中进行返回
            list.add(message);
        }

        return new BaseResp(1,"success",list,null);
    }


}
